﻿using System;
using System.Collections.Generic;
using System.Linq;
using iHouse.Infrastructure;
using iHouse.Model.Data;
using iHouse.Model.Repository.Interface;

namespace iHouse.Model.Repository
{
    public class SqlCategoryRepository : BaseRepository<iHouseDbContext, Category>, ICategoryRepository
    {
        protected override string ContextKey
        {
            get { return "DataContextForCategory"; }
        }

        #region ICategoryRepository Members

        public JqGridList<Category> GetCategoriesForList(int typeID, PagingCriteria criteria)
        {
            IQueryable<Category> result = null;

            if (typeID > 0)
            {
                result = from category in CurrentDataContext.Categories
                         where category.TypeID == typeID
                         orderby category.Name
                         select category;
            }
            else
            {
                result = from category in CurrentDataContext.Categories
                         orderby category.TypeID, category.Name
                         select category;
            }

            return result.ToJqGridList(criteria);
        }

        public IEnumerable<Category> GetCategoriesByType(int typeID)
        {
            var result = from category in CurrentDataContext.Categories
                         where category.TypeID == typeID
                         orderby category.Name
                         select category;

            return result.AsEnumerable();
        }

        public void CreateCategory(Category c)
        {
            CurrentDataContext.Categories.Add(c);
            CurrentDataContext.SaveChanges();
        }

        public void UpdateCategory()
        {
            CurrentDataContext.SaveChanges();
        }

        public void DeleteCategory(int categoryID)
        {
            Category c = CurrentDataContext.Categories.Where(x => x.ID == categoryID).First();

            CurrentDataContext.Categories.Remove(c);
            CurrentDataContext.SaveChanges();
        }

        public Category GetCategoryByID(int categoryID)
        {
            return CurrentDataContext.Categories.Where(x => x.ID == categoryID).First();
        }

        public IEnumerable<IGrouping<int, Category>> GetAllCategories()
        {
            var result = from category in CurrentDataContext.Categories
                         group category by category.TypeID;
            
            return result;
        }

        #endregion


    }
}
